package com.margo.project.web.mvcconfig.requestbodyadvice;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

@ControllerAdvice
public class MargoDataLicenseAdvice extends RequestBodyAdviceAdapter{
	
	private Logger logger=LoggerFactory.getLogger(MargoRequestBodyAdvice.class);	
	
	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		Boolean support=methodParameter.hasParameterAnnotation(DataLicense.class);
		return support;
	}
	
	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		if (body != null) {
			DataLicense anno = parameter.getParameterAnnotation(DataLicense.class);
			String filedName = anno.fieldName();
			String tableName = anno.parkTableName();
			String businessTableName=anno.businessTableName();
			Field field;
			try {
				field =body.getClass().getDeclaredField(filedName);
				field.setAccessible(true);
				DataLicenseVO dataLicenseVO = (DataLicenseVO) field.get(body);
				if(dataLicenseVO==null) {
					dataLicenseVO=new DataLicenseVO();
				}
				dataLicenseVO.setParkTableName(tableName);
				dataLicenseVO.setBusinessTableName(businessTableName);
				field.set(body,dataLicenseVO);
			} catch (Exception e) {
				logger.error("#######属性设置异常######",e);
			} 
			return body;
		} else {
			return body;
		}
	}
}
